package devcontainer

import (
	"code.gitea.io/gitea/modules/log"
	DevcontainersVO "code.gitea.io/gitea/routers/api/devcontainer/vo"
	gitea_web_context "code.gitea.io/gitea/services/context"
	DevcontainersService "code.gitea.io/gitea/services/devstar_devcontainer"
)

// CreateRepoDevContainer 创建仓库 Dev Container
func CreateRepoDevContainer(ctx *gitea_web_context.Context) {
	if !isUserDevcontainerAlreadyInRepository(ctx) {
		opts := &DevcontainersVO.CreateRepoDevcontainerOptions{
			Actor:      ctx.Doer,
			Repository: ctx.Repo.Repository,
		}
		err := DevcontainersService.CreateRepoDevcontainer(ctx, opts)
		if err != nil {
			log.Error("failed to create devContainer with option{%v}: %v", opts, err.Error())
			ctx.Flash.Error(ctx.Tr("repo.dev_container_control.creation_failed_for_user", ctx.Doer.Name))
		} else {
			ctx.Flash.Success(ctx.Tr("repo.dev_container_control.creation_success_for_user", ctx.Doer.Name))
		}
	}

	ctx.Redirect(ctx.Repo.RepoLink + "/dev-container")
}

// isValidRepoDevcontainerJsonFile 辅助判断当前仓库的当前分支是否存在有效的 /.devcontainer/devcontainer.json
func isValidRepoDevcontainerJsonFile(ctx *gitea_web_context.Context) bool {

	// 1. 仓库非空，且非 Archived 状态
	if ctx.Repo.Repository.IsEmpty || ctx.Repo.Repository.IsArchived {
		return false
	}

	// 2. 当前分支的目录 .devcontainer 下存在 devcontainer.json 文件
	fileDevcontainerJsonExists, err := ctx.Repo.FileExists(".devcontainer/devcontainer.json", ctx.Repo.BranchName)
	if err != nil || !fileDevcontainerJsonExists {
		return false
	}

	// 3. TODO: DevContainer 格式正确
	return true
}

// isUserDevcontainerAlreadyInRepository 辅助判断当前用户在当前仓库是否已有 Dev Container
func isUserDevcontainerAlreadyInRepository(ctx *gitea_web_context.Context) bool {

	opts := &DevcontainersVO.RepoDevcontainerOptions{
		Actor:      ctx.Doer,
		Repository: ctx.Repo.Repository,
	}

	devcontainerDetails, _ := DevcontainersService.GetRepoDevcontainerDetails(ctx, opts)
	return devcontainerDetails.DevContainerId > 0
}
